/*
 * @Description:
 * @Author: HYH
 * @email: HYH_0716@163.com
 * @version:
 * @Date: 2025-10-19 13:07:47
 * @LastEditors: your name
 * @LastEditTime: 2025-11-06 17:42:21
 */
import React, { useState, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { RouteConfig } from '../../router/types';
import './index.css';

interface SidebarProps {
  routes: RouteConfig[];
}

const Sidebar: React.FC<SidebarProps> = ({ routes }) => {
  const location = useLocation();
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 初始化：默认展开当前路由的父菜单（无需手动折叠/展开）
  useEffect(() => {
    const getParentKeys = (path: string, routes: RouteConfig[]): string[] => {
      for (const route of routes) {
        if (route.items && route.items.some((item) => path.startsWith(item.path))) {
          return [route.key!, ...getParentKeys(path, route.items)];
        }
      }
      return [];
    };
    setExpandedKeys(getParentKeys(location.pathname, routes));
  }, [location.pathname, routes]);

  // 点击父菜单切换展开/折叠（仅保留基础切换，无折叠按钮）
  const toggleSubMenu = (key: string) => {
    setExpandedKeys((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
    );
  };

  // 渲染单个菜单项（无图标）
  const renderMenuItem = (route: RouteConfig) => {
    const isActive = location.pathname === route.path;
    return (
      <Link
        to={route.path}
        key={route.key}
        className={`sidebar-menu-item ${isActive ? 'active' : ''}`}
      >
        <span className="menu-title">{route.title}</span>
      </Link>
    );
  };

  // 渲染子菜单（无图标、无折叠按钮）
  const renderSubMenu = (route: RouteConfig) => {
    const hasActiveChild = route.items?.some((item) =>
      location.pathname.startsWith(item.path)
    );
    const isExpanded = expandedKeys.includes(route.key!);

    return (
      <div key={route.key} className="sidebar-submenu">
        <div
          className={`submenu-header ${hasActiveChild ? 'active' : ''}`}
          onClick={() => toggleSubMenu(route.key!)}
        >
          <span className="menu-title">{route.title}</span>
          <span className={`expand-icon ${isExpanded ? 'expanded' : ''}`}>
            {isExpanded ? '▼' : '►'}
          </span>
        </div>
        {isExpanded && (
          <div className="submenu-items">
            {route.items?.map((item) => renderMenuItem(item))}
          </div>
        )}
      </div>
    );
  };

  // 渲染所有菜单
  const renderMenu = (routes: RouteConfig[]) => {
    return routes.map((route) =>
      route.items ? renderSubMenu(route) : renderMenuItem(route)
    );
  };

  return (
    <aside className="sidebar-container">
      {/* 菜单列表（核心导航功能） */}
      <nav className="sidebar-menu">{renderMenu(routes)}</nav>
    </aside>
  );
};

export default Sidebar;
